package com.ihisun.tmhcms.core.service.machanismservice.impl;

import com.ihisun.tmhcms.core.dao.citydao.AreaVoDao;
import com.ihisun.tmhcms.core.dao.mechanismdao.*;
import com.ihisun.tmhcms.core.dto.mechanismdto.*;
import com.ihisun.tmhcms.core.service.machanismservice.MachanismService;
import com.ihisun.tmhcms.core.vo.AreaVo;
import com.ihisun.tmhcms.core.vo.MechanismTypeVo;
import com.ihisun.tmhcms.core.vo.MechanismVo;
import com.ihisun.tmhcms.utils.DateUtils;
import com.ihisun.tmhcms.utils.PageBean;
import com.ihisun.tmhcms.utils.ResponseVo;
import com.ihisun.tmhcms.utils.UuIdUtil;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.print.attribute.standard.PageRanges;
import javax.transaction.Transactional;
import java.awt.print.Pageable;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MachsanismServiceImpl implements MachanismService {
    @Resource
    EditMechanismTypeDao EditmechanismTypeDao;
    @Resource
    EditMechanismDao editMechanismDao;
    @Resource
    EditAddressDao editAddressDao;
    @Resource
    EditMechanismDataDao editMechanismDataDao;
    @Resource
    EditSpareDao editSpareDao;
    @Resource
    EditMechanismBannerDao editMechanismBannerDao;
    @PersistenceContext
    EntityManager entityManager;
    @Resource
    MechanismDao mechanismDao;
    @Resource
    MechanismTypeDao mechanismTypeDao;
    @Resource
    AreaVoDao areaVoDao;

    @Override
    public ResponseVo addMachanismType(EditMechanismTypeDto mechanismTypeDto) {
        if (mechanismTypeDto.getTypeId() == null || "".equals(mechanismTypeDto.getTypeId())) {
            mechanismTypeDto.setTypeId(UuIdUtil.getToUuid());
            mechanismTypeDto.setState(1);
            mechanismTypeDto.setCreateTime(DateUtils.getCurrentTime());
            mechanismTypeDto.setUpdateTime(DateUtils.getCurrentTime());
            EditMechanismTypeDto save = EditmechanismTypeDao.save(mechanismTypeDto);
        } else {
            EditMechanismTypeDto byTypeId = EditmechanismTypeDao.findByTypeId(mechanismTypeDto.getTypeId());
            byTypeId.setUpdateTime(DateUtils.getCurrentTime());
            byTypeId.setClassificationName(mechanismTypeDto.getClassificationName());
            byTypeId.setTypeOne(mechanismTypeDto.getTypeOne());
            byTypeId.setTypeTwo(mechanismTypeDto.getTypeTwo());
            byTypeId.setTypeThree(mechanismTypeDto.getTypeThree());
            EditmechanismTypeDao.save(byTypeId);
        }
        return ResponseVo.ok();
    }

    /**
     * 删除机构分类
     *
     * @param typeId     分类Id
     * @param valueState 状态值
     * @return
     */
    @Override
    public ResponseVo deleteMchanismType(String typeId, Integer valueState) {
        List<MechanismVo> byMechanismClassification = mechanismDao.findByMechanismClassification(typeId);
        if (byMechanismClassification != null && !byMechanismClassification.isEmpty()) {
            return ResponseVo.error();
        } else {
            EditMechanismTypeDto byTypeId = EditmechanismTypeDao.findByTypeId(typeId);
            byTypeId.setState(valueState);
            byTypeId.setUpdateTime(DateUtils.getCurrentTime());
            EditmechanismTypeDao.save(byTypeId);
            return ResponseVo.ok();
        }
    }

    /**
     * 编辑机构
     *
     * @param editMechanismDto
     * @return
     */
    @Transactional
    @Override
    public ResponseVo editMechanism(EditMechanismDto editMechanismDto) {
        if (editMechanismDto.getMechanismId() != null && !"".equals(editMechanismDto.getMechanismId())) {
            //修改
            /**
             * 修改机构主体信息
             */
            editMechanismDto.setUpdateTime(DateUtils.getCurrentTime());
            editMechanismDao.save(editMechanismDto);
            /**
             * 删除机构地址
             */
            editAddressDao.deleteByMechanismId(editMechanismDto.getMechanismId());
            /**
             * 保存新地址
             */
            EditAddressDto mAddress = editMechanismDto.getMAddress();
            mAddress.setCreateTime(DateUtils.getCurrentTime());
            mAddress.setUpdateTime(DateUtils.getCurrentTime());
            mAddress.setMechanismId(editMechanismDto.getMechanismId());
            editAddressDao.save(editMechanismDto.getMAddress());
            /**
             * 删除认证质料
             */
            editMechanismDataDao.deleteByMechanismId(editMechanismDto.getMechanismId());
            /**
             * 保存新的认证资料
             */
            List<EditMechanismDataDto> mechanismDataDtos = editMechanismDto.getMechanismDataDtos();
            for (int i = 0; i < mechanismDataDtos.size(); i++) {
                mechanismDataDtos.get(i).setUpdateTime(DateUtils.getCurrentTime());
                mechanismDataDtos.get(i).setCreateTime(DateUtils.getCurrentTime());
                mechanismDataDtos.get(i).setMechanismId(editMechanismDto.getMechanismId());
                editMechanismDataDao.save(mechanismDataDtos.get(i));
            }
            /**
             * 删除机构备用联系人
             */
            editSpareDao.deleteByMechanismId(editMechanismDto.getMechanismId());
            /**
             * 保存机构备用联系人
             */
            List<EditSpareDto> spareDtos = editMechanismDto.getSpareDtos();
            for (int i = 0; i < spareDtos.size(); i++) {
                spareDtos.get(i).setMechanismId(editMechanismDto.getMechanismId());
                spareDtos.get(i).setCreateTime(DateUtils.getCurrentTime());
                spareDtos.get(i).setUpdateTime(DateUtils.getCurrentTime());
                editSpareDao.save(spareDtos.get(i));
            }
            /**
             * 删除轮播
             */
            editMechanismBannerDao.deleteByMechanismId(editMechanismDto.getMechanismId());
            /**
             * 保存轮播
             */
            List<EditMechanismBannerDto> mechanismBannerDtos = editMechanismDto.getMechanismBannerDtos();
            for (int i = 0; i < mechanismBannerDtos.size(); i++) {
                mechanismBannerDtos.get(i).setMechanismId(editMechanismDto.getMechanismId());
                mechanismBannerDtos.get(i).setCreateTime(DateUtils.getCurrentTime());
                mechanismBannerDtos.get(i).setUpdateTime(DateUtils.getCurrentTime());
                editMechanismBannerDao.save(mechanismBannerDtos.get(i));
            }
        } else {
            String uuid = DateUtils.getCurrentTime();
            //添加
            /**
             * 保存机构
             */
            editMechanismDto.setUpdateTime(uuid);
            editMechanismDto.setCreateTime(DateUtils.getCurrentTime());
            editMechanismDto.setMechanismId(UuIdUtil.getToUuid());
            EditMechanismDto save = editMechanismDao.save(editMechanismDto);
            /**
             * 保存机构地址
             */
            EditAddressDto mAddress = editMechanismDto.getMAddress();
            mAddress.setUpdateTime(DateUtils.getCurrentTime());
            mAddress.setCreateTime(DateUtils.getCurrentTime());
            mAddress.setMechanismId(uuid);
            editAddressDao.save(mAddress);
            /**
             * 保存轮播
             */
            List<EditMechanismBannerDto> mechanismBannerDtos = editMechanismDto.getMechanismBannerDtos();
            for (int i = 0; i < mechanismBannerDtos.size(); i++) {
                mechanismBannerDtos.get(i).setMechanismId(uuid);
                mechanismBannerDtos.get(i).setCreateTime(DateUtils.getCurrentTime());
                mechanismBannerDtos.get(i).setUpdateTime(DateUtils.getCurrentTime());
                editMechanismBannerDao.save(mechanismBannerDtos.get(i));
            }
            /**
             *保存执照
             */
            List<EditMechanismDataDto> mechanismDataDtos = editMechanismDto.getMechanismDataDtos();
            for (int i = 0; i < mechanismDataDtos.size(); i++) {
                mechanismDataDtos.get(i).setUpdateTime(DateUtils.getCurrentTime());
                mechanismDataDtos.get(i).setCreateTime(DateUtils.getCurrentTime());
                mechanismDataDtos.get(i).setMechanismId(uuid);
                editMechanismDataDao.save(mechanismDataDtos.get(i));
            }
            /**
             * 保存备用联系人
             */
            List<EditSpareDto> spareDtos = editMechanismDto.getSpareDtos();
            for (int i = 0; i < spareDtos.size(); i++) {
                spareDtos.get(i).setCreateTime(DateUtils.getCurrentTime());
                spareDtos.get(i).setUpdateTime(DateUtils.getCurrentTime());
                spareDtos.get(i).setMechanismId(uuid);
                editSpareDao.save(spareDtos.get(i));
            }

        }


        return ResponseVo.ok();
    }

    @Override
    public ResponseVo searchMechanism(SearchMechanismDto searchMechanismDto) {
        StringBuilder sql = new StringBuilder();
        //select * from m_mechanism where mechanism_name LIKE concat('%','美','%') or phone LIKE concat('%','1','%') or city=028 or nature=1 or state=1
        sql.append("select * from m_mechanism where 1=1");
        if (searchMechanismDto.getMechanismName() != null && !"".equals(searchMechanismDto.getMechanismName())) {
            sql.append(" or mechanism_name LIKE concat('%','" + searchMechanismDto.getMechanismName() + "','%') ");
        }
        if (searchMechanismDto.getLegalPersonPhone() != null && !"".equals(searchMechanismDto.getLegalPersonPhone())) {
            sql.append(" or legal_person_phone LIKE concat('%','" + searchMechanismDto.getLegalPersonPhone() + "','%')");
        }
        if (searchMechanismDto.getNature() != null && !"".equals(searchMechanismDto.getNature())) {
            sql.append(" or nature='" + searchMechanismDto.getNature() + "'");
        }
        if (searchMechanismDto.getCity() != null && !"".equals(searchMechanismDto.getCity())) {
            sql.append(" or city='" + searchMechanismDto.getCity() + "'");
        }
        if (searchMechanismDto.getState() != null) {
            sql.append(" or state=" + searchMechanismDto.getState() + "");
        }
        sql.append(" limit " + (searchMechanismDto.getPageNum() - 1) * 10 + "," + searchMechanismDto.getPageSize());

        List<MechanismVo> resultList = entityManager.createNativeQuery(sql.toString(), MechanismVo.class).getResultList();
        StringBuilder countSql = new StringBuilder();
        countSql.append("select count(*) from m_mechanism where 1=1");

        if (searchMechanismDto.getMechanismName() != null && !"".equals(searchMechanismDto.getMechanismName())) {
            countSql.append(" or mechanism_name LIKE concat('%','" + searchMechanismDto.getMechanismName() + "','%') ");
        }
        if (searchMechanismDto.getLegalPersonPhone() != null && !"".equals(searchMechanismDto.getLegalPersonPhone())) {
            countSql.append(" or legal_person_phone LIKE concat('%','" + searchMechanismDto.getLegalPersonPhone() + "','%')");
        }
        if (searchMechanismDto.getNature() != null && !"".equals(searchMechanismDto.getNature())) {
            countSql.append(" or nature='" + searchMechanismDto.getNature() + "'");
        }
        if (searchMechanismDto.getCity() != null && !"".equals(searchMechanismDto.getCity())) {
            countSql.append(" or city='" + searchMechanismDto.getCity() + "'");
        }
        if (searchMechanismDto.getState() != null) {
            countSql.append(" or state=" + searchMechanismDto.getState() + "");
        }
        countSql.append(" limit " + (searchMechanismDto.getPageNum() - 1) * 10 + "," + searchMechanismDto.getPageSize());

        log.info("sql=" + sql);
        log.info("count=" + countSql);

        BigInteger singleResult = (BigInteger) entityManager.createNativeQuery(countSql.toString()).getSingleResult();
        PageBean pageBean = new PageBean(searchMechanismDto.getPageSize(), singleResult.intValue(), searchMechanismDto.getPageNum(), resultList);
        return ResponseVo.ok(pageBean);
    }

    @Override
    public ResponseVo searchMechanismType(String mechanismTypeName, Integer pageNum, Integer pageSize) {

        Page<MechanismTypeVo> byClassificationName = null;
        PageRequest of = PageRequest.of(pageNum, pageSize);
        if (mechanismTypeName != null && !"".equals(mechanismTypeName)) {

            byClassificationName = mechanismTypeDao.findByClassificationName(of, mechanismTypeName);
        } else {
            byClassificationName = mechanismTypeDao.findByLimit(of);
        }
        List<MechanismTypeVo> content = byClassificationName.getContent();
        for (int i = 0; i < content.size(); i++) {
            Integer integer = mechanismDao.countByMechanismClassificationAndStateNot(content.get(i).getTypeId(), 3);
            if (integer == null) {
                content.get(i).setMechanismNumber("0");
            } else {
                content.get(i).setMechanismNumber(String.valueOf(integer));
            }
        }
        return ResponseVo.ok(byClassificationName);
    }

    @Override
    public ResponseVo findByNoMechanism() {
        Map<String, Object> map = new HashMap<>();
        List<AreaVo> all = areaVoDao.findAll();
        for (int i = 0; i < all.size(); i++) {
            List<MechanismVo> byCity = mechanismDao.findByCity(all.get(i).getCityCode());
            map.put(all.get(i).getName(), byCity);
        }
        return ResponseVo.ok(map);
    }

    @Override
    public ResponseVo findByMechanism(String keeperId) {
        List<MechanismVo> byHousekeeperId = mechanismDao.findByHousekeeperId(keeperId);
        return ResponseVo.ok(byHousekeeperId);
    }
}
